﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppNetworkTestAndToEmail
{
    /// <summary>
    /// 字符串Hash签名
    /// </summary>
    /// 2022-1-4 16:15:03 王浩力 添加
    public static class HashEncrypt
    {
        /// <summary>
        /// SHA1签名生成40位16进制字符串
        /// </summary>
        /// <param name="input">待签名字符串</param>
        /// <returns></returns>
        /// 创建时间：2022-5-31 14:51:39。作者：王浩力
        public static string Sha1bit40(string input)
        {
            string encryptKey = "";
            ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();
            byte[] tmpByte = aSCIIEncoding.GetBytes(input);
            HMACSHA1 hmac = new HMACSHA1(aSCIIEncoding.GetBytes(encryptKey));
            byte[] jmBytes = hmac.ComputeHash(tmpByte);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < jmBytes.Length; i++)
            {
                builder.Append(jmBytes[i].ToString("X2"));
            }
            hmac.Clear();
            return builder.ToString();
        }

        /// <summary>
        ///SHA256 位字符串Hash签名
        /// </summary>
        /// <param name="strIN"></param>
        /// <returns></returns>
        public static string SHA256Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA256 sha256 = new SHA256Managed();
            tmpByte = sha256.ComputeHash(GetKeyByteArray(strIN));
            sha256.Clear();
            return GetStringValue(tmpByte);
        }

        /// <summary>
        /// SHA512 位字符串Hash签名
        /// </summary>
        /// <param name="strIN"></param>
        /// <returns></returns>
        public static string SHA512Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA512 sha512 = new SHA512Managed();
            tmpByte = sha512.ComputeHash(GetKeyByteArray(strIN));
            sha512.Clear();
            return GetStringValue(tmpByte);
        }


        public static byte[] GetKeyByteArray(string strKey)
        {
            ASCIIEncoding Asc = new ASCIIEncoding();
            int tmpStrLen = strKey.Length;
            byte[] tmpByte = new byte[tmpStrLen - 1];
            tmpByte = Asc.GetBytes(strKey);
            return tmpByte;
        }

        /// <summary>
        /// 将byte字节数组转换为大写的16进制字符串
        /// </summary>
        /// <param name="bytes">byte字节数组</param>
        /// <returns></returns>
        public static string GetStringValue(byte[] bytes)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("X2"));
            }
            return builder.ToString();
        }

    }
}
